

import signal
from threading import Thread
import cv2
import sys
import numpy as np
from minicpmv import MiniCPMV
from capture import VideoCapture


# 捕获 Ctrl+C 事件
def signal_handler(sig, frame):
    print("\n程序正在退出... ")
    if gpt:
        gpt.release()
    if capture:
        capture.release()
    print("程序退出。")
    exit(0)


def show_capture(capture: VideoCapture):
    while capture.isRUN:
        img = capture.read()
        cv2.imshow("capture", img)
        cv2.waitKey(1)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)  # 注册 Ctrl+C 信号处理器

    model_path = "checkpoints/model.rkllm"
    vision_path = "checkpoints/vision-384.rknn"
    gpt = MiniCPMV(model_path, vision_path)
    capture = VideoCapture("http://10.193.190.99:4747/video")

    # 显示线程
    show_capture_thread = Thread(target=show_capture, args=(capture,), daemon=True)
    show_capture_thread.start()

    # gpt在主线程中推理
    while True:
        ipt = input("按回车键开始推理(exit退出): ")
        if ipt == "exit":
            break
        img = capture.read()
        prepared_image = gpt.prepare_image(img)
        print("AI:", end=" ", flush=True)
        gpt.run(prepared_image, f"<image>图片有什么？")



